var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
Page({
  data: {
    motto: '请稍等\n\n正在识别您的身份',
    userInfo: {},
    multiuser:false,
    multiuserSelected:false,
    auth_result:false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    hasUserInfo:false,
    hasUserLocation: false,
    is_signing_show:false,
    is_agree_requirement:false,
    roles_result: false,
    register:false,
    indexAdv:false,
    reload:false,
    modalName:''
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  phoneauth: function() {
    wx.navigateTo({
      url: '/pages/auth/phoneauth'
    })
  },
  driverreg: function() {
    wx.navigateTo({
      url: '/pages/auth/phoneauth' 
    }) 
  },
  onShow:function(){
    var that = this;
    try {
      var CO_NAME = wx.getStorageSync('CO_NAME')
      if (CO_NAME) {
          this.setData({
            CO_NAME:CO_NAME
          })
      }
      var truename = wx.getStorageSync('truename')
      if (truename) {
          this.setData({
            truename:truename
          })
      }
    } catch (e) {}
  },
  onReady: function () {
    try {
      var CO_NAME = wx.getStorageSync('CO_NAME')
      if (CO_NAME) {
          this.setData({
            CO_NAME:CO_NAME
          })
      }
      var truename = wx.getStorageSync('truename')
      if (truename) {
          this.setData({
            truename:truename
          })
      }
    } catch (e) {}
    wx.hideToast();
  },
  onLoad: function (e) {
    var that = this;

    // wx.redirectTo({
    //   url: '/pages/driver/order_receiver?id=6&show=true'
    // })
    // return false;

    wx.onNetworkStatusChange(function (res) {
      if(!res.isConnected){
        wx.showModal({
          title: '温馨提示',
          content: '网络异常，请检查网络！',
          success(res) {
            if (res.confirm) {
              console.log('网络异常，请检查网络！')
            }
          }
        })
      }
    })

    wx.setNavigationBarTitle({ "title": app.appName });
    if(e.page){
      that.setData({
        page:e.page
      })
    }
    if (e.reload) {
      that.setData({
        reload: e.reload
      })
    }
    if (e.type) {
      that.setData({
        type: e.type
      })
      app.globalData.userType = e.type;
    }
    that.setData({
      appName: app.appName,
      is_login:app.globalData.is_login
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          middle_height: res.windowHeight,
          client_width: res.windowWidth,
          client_height: res.windowHeight
        });
      }
    });
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log('=================调试============')
        console.log(res.authSetting)
        if (res.authSetting["scope.userInfo"] == true){
          that.setData({
            hasUserInfo:true
          })
        }
        if (res.authSetting["scope.userLocation"] == true) {
          that.setData({
            hasUserLocation: true
          })
        }else{
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              // wx.redirectTo({
              //   url: '/pages/index/index',
              // })
            }
          })
        }
        if (res.authSetting["scope.userLocationBackground"] == true) {
           app.globalData.userLocationBackground = true;
        }else{
          app.globalData.userLocationBackground = false;
        }

        if (that.data.hasUserInfo == true){
          that.setData({
            auth_result:true
          })
          that.initPage();
        }else{
          //隐藏广告页
          that.setData({
            indexAdv: true
          })
        }
      }
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    wx.request({
      url: app.server + '/wechat/passport/getPhoneNumber',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Cookie':app.globalData.cookie
      },
      data: {
        sessionKey: app.globalData.session_key,
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv
      },
      success: function (res) {
        console.log(res);
        wx.redirectTo({
          url: '/pages/auth/phoneauth?phone=' + res.data.data.purePhoneNumber
        })
      },
      fail: function (error) {
        wx.redirectTo({
          url: '/pages/auth/phoneauth'
        })
        console.log(error);
      }
    })
  },
  phoneauth:function(){
    wx.redirectTo({
      url: '/pages/auth/phoneauth'
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  experience: function () {
    this.setData({
      modalName: 'experienceModal'
    })
  },
  experienceDriver:function(){
    var that = this;
    if (that.data.experienceUser != '138138'){
      wx.showToast({
        title: "体验账户错误",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    if (that.data.experiencePassword != '831831') {
      wx.showToast({
        title: "体验密码错误",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    app.globalData.openid = 'oH_mR6y69seyeSV5SaSKMrLFqvuI';
    app.globalData.unionid = 'oGxUoxE5kkKbRLmlOBcQVyBZkyLo';
    app.globalData.register = '';
    app.globalData.userData = '';
    app.globalData.mpopenid = '';
    app.globalData.mobile = '';
    app.globalData.truename = '体验用户';
    app.globalData.wh_id = '';
    app.globalData.admin = 0;
    app.globalData.coAdmin = 0;
    app.globalData.vehicleId = 470;
    app.globalData.driverId = 470;
    app.globalData.share = 1;
    app.globalData.user_id = 1;
    app.globalData.CO_ID = 61;
    app.globalData.is_verify = 1;
    app.globalData.id_card = '2222';
    wx.redirectTo({
      url: '/pages/driver/orderList',
    })
  },
  experienceSchedule: function () {
    var that = this;
    if (that.data.experienceUser != '138138') {
      wx.showToast({
        title: "体验账户错误",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    if (that.data.experiencePassword != '831831') {
      wx.showToast({
        title: "体验密码错误",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    app.globalData.openid = 'omz4L0enOIdFBhba15ZECgFN47JE';
    app.globalData.unionid = 'oGxUoxE5kkKbRLmlOBcQVyBZkyLo';
    app.globalData.register = '';
    app.globalData.userData = '';
    app.globalData.mpopenid = '';
    app.globalData.mobile = '';
    app.globalData.truename = '体验用户';
    app.globalData.wh_id = '';
    app.globalData.admin = 0;
    app.globalData.coAdmin = 0;
    app.globalData.share = 1;
    app.globalData.user_id = 1;
    app.globalData.CO_ID = 61;
    wx.redirectTo({
      url: '/pages/schedule/schedule',
    })
  },
  getUserLocation:function(){
    // console.log(this.data.hasUserLocation)
    // wx.authorize({
    //   scope: 'scope.userLocation',
    //   success() {
    //     wx.redirectTo({
    //       url: '/pages/index/index',
    //     })
    //   }
    // })
    wx.openSetting({
      success(res) {
        console.log(res.authSetting)
      }
    })
  },
  reload:function(){
    var that = this;
    //调用应用实例的方法获取全局数据
    // app.getUserInfo(function (login, error) {
    //   console.log(login)
    //   console.log(error);
    // })
    
    that.initPage();
  },
  refreshPage:function(){
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  callService:function(){
    wx.makePhoneCall({
      phoneNumber: '4009971568'
    })
  },
  initPage:function(){
    var that = this;

    // if (app.globalData.role_default && !that.data.reload){
    //   that.intoRolePage(app.globalData.role_default);
    //   return false;
    // }
    console.log('开始登录。。。。。。。。。。')
    app.getUserInfo(function (register) {
      //隐藏广告页
      // that.setData({
      //   indexAdv: true
      // })
      that.setData({
        register: register
      })
      console.log('登录结果',register);
      console.log(app.globalData.roles);
      if (app.globalData?.roles?.length > 0){
        that.intoRolePage();
        //app.checkOfficialAccounts(function (data) {
        //  that.intoRolePage(role_default);
          // if (data == 'follow') {
          //   that.intoRolePage(role_default);
          // } else if (data == 'follow_no_connection') {
          //   wx.showModal({
          //     title: '温馨提示',
          //     content: '您已关注【' + app.appName + '】公众号，但未关联【' + app.appName +'】小程序。请按”确认"关联。',
          //     confirmText: '确认',
          //     cancelText: '取消',
          //     success(res) {
          //       if (res.confirm) {
          //         wx.navigateTo({
          //           url: '/pages/index/index'
          //         })
          //       }
          //     }
          //   })
          // } else if (data == 'no_follow') {
          //   wx.showModal({
          //     title: '温馨提示',
          //     content: '您尚未关注公众号【' + app.appName + '】，系统需要通过公众号来推送业务信息。请搜索公众号【' + app.appName +'】并且关注。',
          //     confirmText: '已关注',
          //     cancelText: '取消',
          //     success(res) {
          //       if (res.confirm) {
          //         wx.navigateTo({
          //           url: '/pages/index/index'
          //         })
          //       }
          //     }
          //   })
          // }
        //});
      }else{
        that.setData({
          roles_result: false,
          indexAdv:true
        })
        if (app.globalData.roles == false && app.globalData.CO_ID != '' && app.globalData.CO_ID != undefined && app.globalData.truename != '' && app.globalData.truename != undefined){
          wx.showModal({
            title: '温馨提示',
            content: '请联系你所在企业的管理员开通管理权限！',
            showCancel:false,
            success: function (res) {
              wx.redirectTo({
                url: '/pages/index/index'
              })
            }
          })
        }
      }
    })
  },
  intoRolePage: function () {
    var that = this;
    // wx.redirectTo({
    //   //url: '/pages/enterprise/price_config?type=warehouse&id=470'
    //   url:'/pages/auth/phoneauth'
    //   //url:'/pages/erp/finance/cost_reimbursement_form?CO_ID=61&flow_node=1&approve_role=|42&id=1133'
    //   //url:'/pages/vehicle/vehicle_detail?id=645'
    //   //url: '/pages/report/pages/monthly_statement'
    //   //url: '/pages/index/deliveryForm'
    //   //url:'/pages/report/pages/monthly_statement'
    //   //url: '/pages/report/pages/vehicle_delivery_report'
    //   //url: '/pages/enterprise/price_config?type=warehouse&id=522'
    //   //url: '/pages/enterprise/price_config?type=warehouse&id=522'
    //   //url: '/pages/driver/currentOrder'
    //   //url: '/pages/report/pages/monthly_statement'
    //   //url: '/pages/driver/currentOrder?id=ad957c135f274bb4a8e87f3ff03f4849'
    //   //url: '/pages/schedule/vehicle'
    //   //url:'/pages/vehicle/vehicle_detail?id=645'
    // }) 
    // return false;
    if(!app.globalData.is_login){
      wx.showModal({
        title: '温馨提示',
        content: '请联系你所在企业的管理员开通管理权限！',
        showCancel:false,
        success: function (res) {
          wx.redirectTo({
            url: '/pages/index/index'
          })
        }
      })
       return false;
    }
    if(app.globalData.CO_NAME){
      try {
        wx.setStorageSync('CO_NAME', app.globalData.CO_NAME||app.globalData.customerMame)
      } catch (e) { }
    }
    if(app.globalData.truename){
      try {
        wx.setStorageSync('truename', app.globalData.truename)
      } catch (e) { }
    }
    // wx.requestSubscribeMessage({
    //   tmplIds: ['iYtKTmqMl0fjMQWn8zMA-EaPH604Q9znKxCE5f-JpPE','pveXCmc0DrvNxBSLum2m8jCE-2R6MBkKkhD230r9gC8'],
    //   success (res) {
    //     console.log(res)
    //    }
    // })
    if (that.data.page) {
      wx.redirectTo({
        url: that.data.page
      })
      return false;
    }
    if (app.globalData.roles.indexOf('||customer|||') > 0) {//客户
      wx.redirectTo({
        url: '/pages/customer/orderList'
      })
      //app.setWXLocation("driver");
    } else if (app.globalData.roles.indexOf('||driver|||') > 0) {//司机会员
      wx.redirectTo({
        url: '/pages/driver/orderList'
      })
      //app.setWXLocation("driver");
    } else if (app.globalData.roles.indexOf('||admin|||') > 0) {//企业会员
      wx.redirectTo({
        url: '/pages/enterprise/enterprise'
      })
    } else if (app.globalData.roles.indexOf('||operation|||') > 0) {//运营管理会员
      wx.redirectTo({
        url: '/pages/enterprise/enterprise'
      })
    } else if (app.globalData.roles.indexOf('||scheduler|||') > 0) {//客服跟单员
      wx.redirectTo({
        url: '/pages/schedule/schedule'
      })
      //app.setWXLocation("schedule");
    } else if (app.globalData.roles.indexOf('||fleet|||') > 0) {//运力调度员
      wx.redirectTo({
        url: '/pages/fleet/fleet'
      })
    } else if (app.globalData.roles.indexOf('||finance|||') > 0) {//财务结算员
      wx.redirectTo({
        url: '/pages/finance/finance'
      })
    }else{
      console.log(11111111)
    }
  },
  regDriver: function () {
    wx.redirectTo({
      url: '/pages/auth/driverreg',
    })
  },
  regManager: function () {
    wx.redirectTo({
      url: '/pages/auth/managerReg',
    })
  },
  regEnterprise: function () {
    wx.redirectTo({
      url: '/pages/auth/enterpriseReg',
    })
  },
  bindGetUserInfo:function(){
     wx.redirectTo({
       url: '/pages/index/index',
     })
  },
  pageTurning:function(){
    var that = this;

    

    if (that.data.page) {
      wx.redirectTo({
        url: that.data.page
      })
    }



    //更新数据
    // that.setData({
    //   userInfo: app.globalData.userInfo,
    //   is_signing:app.globalData.is_signing,
    //   userType: app.globalData.userType
    // });
    // console.log(app.globalData.userType);
    // if (app.globalData.userType) {
    //   var url;
    //   if (app.globalData.userType != "shipper" && app.globalData.userType != "receiver"){
    //     if (app.globalData.data.length > 1 && that.data.multiuserSelected == false) {
    //       var data = app.globalData.data;
    //       for (var i = 0; i < data.length; i++) {
    //         var item = data[i].userType + '_user', item_value = {};
    //         item_value[item] = true;
    //         that.setData(item_value);
    //       }
    //       that.setData({
    //         multiuser: true
    //       });
    //     }
    //     if (app.globalData.data.length > 1 && that.data.multiuserSelected == false) {
    //       return false;
    //     }
    //   }
      
    //   if (app.globalData.userType == "driver") {
    //     app.setDriverLocation("driver");
    //     if (!app.globalData.truename) {
    //       url = '/pages/auth/driverreg?id=' + app.globalData.user_id;
    //     } else {
    //       if (app.globalData.is_signing == '0') {
    //         wx.showLoading({
    //           title: '验证签约中...'
    //         });
    //         util.getData("signingInfo", {
    //           user_id: app.globalData.user_id
    //         }, function (res, error) {
    //           console.log(error)
    //           if (error) {
    //             wx.hideLoading();
    //           }
    //           if (res.data.success) {
    //             wx.hideLoading();
    //             var data = res.data.data[0][0];
    //             var is_employee = res.data.data[1][0].is_employee;
    //             if (is_employee == '0') {
    //               that.setData({
    //                 is_signing_show: true
    //               })
    //               that.setData({
    //                 signing_docs: util.html_decode(data.docs),
    //                 signing_update_date: data.update_date,
    //                 signing_agree_text: data.agree_text,
    //               })
    //             } else {
    //               wx.redirectTo({
    //                 url: url
    //               })
    //             }
    //           } else {
    //             wx.hideLoading();
    //           }
    //         });
    //         return false;
    //       }
    //       url = '/pages/driver/orderList';
    //     }
    //     wx.redirectTo({
    //       url: url
    //     })
    //   } else if (app.globalData.userType == "vehicle") {
    //     if (app.globalData.vehicle == "0") {
    //       url = '/pages/auth/vehiclereg';
    //     } else {
    //       url = '/pages/vehicle/vehicle';
    //     }
    //     wx.redirectTo({
    //       url: url
    //     })
    //   } else if (app.globalData.userType == "receiver"){
    //     url = '/pages/' + app.globalData.userType + '/' + app.globalData.userType;
    //     wx.redirectTo({
    //       url: url
    //     })
    //   } else if (app.globalData.userType == "warehouse") {
    //     url = '/pages/' + app.globalData.userType + '/' + app.globalData.userType;
    //     wx.redirectTo({
    //       url: url
    //     })
    //   } else if (app.globalData.userType == "fleet") {
    //     app.setDriverLocation("fleet");
    //     url = '/pages/' + app.globalData.userType + '/' + app.globalData.userType;
    //     wx.redirectTo({
    //       url: url
    //     })
    //   } else if (app.globalData.userType == "business") {
    //     url = '/pages/' + app.globalData.userType + '/' + app.globalData.userType;
    //     wx.redirectTo({
    //       url: url
    //     })
    //   } else if (app.globalData.userType == "schedule") {
    //     app.setDriverLocation("schedule");
    //     url = '/pages/' + app.globalData.userType + '/' + app.globalData.userType;
    //     wx.redirectTo({
    //       url: url
    //       //url:'/pages/schedule/transport_capacity'
    //     })
    //   }
    //   //  else {
    //   //   url = '/pages/index/deliveryForm?delivery=true';
    //   //   wx.redirectTo({
    //   //     url: url
    //   //   })
    //   // };
      
    // } 
    // else {
    //   // that.setData({
    //   //   auth_result: true
    //   // })
    //   url = '/pages/index/deliveryForm';
    //   wx.redirectTo({
    //     url: url
    //   })
    // }
  },
  changeSigningAgree:function(e){
    if (e.detail.value == '1') {
      this.setData({
        is_agree_requirement: true
      })
    } else {
      this.setData({
        is_agree_requirement: false
      })
    }
  },
  signing_close: function () {
    wx.redirectTo({
      url: '/pages/index/index'
    });
  },
  signing_ok: function () {
    var that = this;
    var is_agree_requirement = this.data.is_agree_requirement;
    if (!is_agree_requirement) {
      wx.showToast({
        title: "请先打勾",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    } else {
      that.setData({
        is_agree_requirement: false
      })
      util.postData("agreeSigning", {
        user_id: app.globalData.user_id
      }, function (res) {
        if (res.data.success) {
          that.setData({
            is_signing: '1',
            is_signing_show:false
          });
          app.globalData.is_signing = '1';
          wx.showToast({
            title: res.data.data,
            icon: 'success',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/index/index'
                });
              }, 2000);
            }
          });
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 2000
          });
        }
      });
    }
  }
})
